/*
 * Copyright (c) 2009 Sun Microsystems, Inc.
 * Copyright (c) 2011 Oracle Corporation.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to
 * deal in the Software without restriction, including without limitation the
 * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
 * sell copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 **/

package org.sunspotworld.demo;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import com.sun.spot.ipv6.io.j2me.tcp.TCPConnection;
import com.sun.spot.ipv6.io.j2me.udp.UDPConnection;
import java.util.Date;
import javax.microedition.io.Connector;
import javax.microedition.io.Datagram;
import com.sun.spot.wot.http.DecodingException;
import com.sun.spot.wot.http.EncodingException;
import com.sun.spot.wot.http.HttpResponse;
import com.sun.spot.wot.http.HttpRequest;

/**
 *
 * @author vgupta
 */
public class HttpClient {
    String connStr = null;
    UDPConnection udpConn = null;
    TCPConnection tcpConn = null;
    boolean useTCP = false;
    boolean useCompression = false;

    public HttpClient(String connection, boolean useCompression) throws IOException {
        this.connStr = connection;
        this.useCompression = useCompression;
        if (connStr.startsWith("udp://")) {
            udpConn = (UDPConnection) Connector.open(connStr);
            udpConn.setTimeout(10000);
            useTCP = false;
        } else if (connStr.startsWith("tcp://")) {
            tcpConn = (TCPConnection) Connector.open(connStr);
            useTCP = true;
        } else {
            throw new IOException("Unsupported connection type in " +
                    connection);
        }
    }

    public HttpResponse sendData(HttpRequest req) throws IOException {
        HttpResponse resp = new HttpResponse();
        byte[] dataOut = new byte[WoTConstants.MAX_HTTPMSG_SIZE];
        int dataOutLength = -1;

        try {
            dataOutLength = req.toByteArray(useCompression, dataOut, 0);
        } catch (EncodingException ex) {
            ex.printStackTrace();
            throw new IOException("Could not encode request");
        }

        if (useTCP) {
            OutputStream os = tcpConn.openOutputStream();
            InputStream is = tcpConn.openInputStream();
            os.write(dataOut, 0, dataOutLength);
            try {
                resp.parse(is);
            } catch (DecodingException ex) {
                ex.printStackTrace();
                throw new IOException("Could not decode response");
            }
        } else {
            Datagram dg = udpConn.newDatagram(udpConn.getMaximumLength());
            dg.write(dataOut, 0, dataOutLength);
            Date date = new Date(System.currentTimeMillis());
//            System.out.println("On " + date + ", sending UDP data to " + connStr);
            udpConn.send(dg);
//            System.out.println("Waiting to receive UDP data from " + connStr);
            dg.reset();
            udpConn.receive(dg);
            byte[] dataIn = dg.getData();
            int dataInLength = dataIn.length;
            try {
                resp = HttpResponse.parse(dataIn, 0, dataInLength);
            } catch (DecodingException ex) {
                ex.printStackTrace();
                throw new IOException("Could not decode response");
            }
        }
        return resp;
    }

    void shutDown() {
        try {
            if (connStr.startsWith("udp")) {
//                System.out.println("Closing UDP connection");
                udpConn.close();
            }
            if (connStr.startsWith("tcp")) {
//                System.out.println("Closing TCP connection");
                tcpConn.close();
            }
        } catch (IOException ioe) {
            System.out.println("Caught " + ioe +
                    " in side HttpClient.shutDown");
            ioe.printStackTrace();
        }
    }
}
